package eraserhead.controller;

import client.ServerAccess;
import eraserhead.boundary.ChoicePanel;
import eraserhead.boundary.WarningWindow;
import eraserhead.entity.Decision;
import eraserhead.entity.Line;
import eraserhead.xml.request.AddChoiceRequest;
import eraserhead.xml.request.CreateClosedRequest;

/**
 * Controller for setting choices.
 * @author Kevin
 * @author Quanquan
 * @author Greg
 */
public class SetChoiceController {
	
	Decision model;
	
	ChoicePanel view;
	
	int position;
	
	/**
	 * Create a new {@link SetChoiceController}
	 * @param model {@link Decision} model to control
	 * @param view {@link ChoicePanel} associated with this {@link Decision}
	 * @param position Position in the {@link Decision} to control
	 */
	public SetChoiceController(Decision model, ChoicePanel view, int position) {
		this.model = model;
		this.view = view;
		this.position = position;
	}
	
	public void process() {
		if (!model.isValidChoice(position, view.getChoiceField(position).getText())) {
			WarningWindow.giveWarning(null, model.getErrorMsg());
			return;
		}
		if (model.isOpen()) {
			System.out.println("AddChoiceRequest was just sent" 
					+ "  id: " + model.getId() 
					+ "  choice name: " + view.getChoiceField(position).getText() 
					+ "  position: " + position);
			AddChoiceRequest.send(ServerAccessManager.getAccess(), 
					model.getId(), view.getChoiceField(position).getText(), position);
		} else {
			model.setChoice(position, view.getChoiceField(position).getText());
			view.getChoiceField(position).setEditable(false);
			for (Line l : model.getLines()) {
				if (l.getChoice().length() == 0) {
					return;
				}
			}
			String[] choices = new String[model.getNumUsers()];
			for (Line l : model.getLines()) {
				choices[l.getPosition()] = l.getChoice();
			}
			ServerAccess sa = ServerAccessManager.getAccess();
			CreateClosedRequest.send(sa, model.getQuestion(), model.getNumUsers(), model.getNumRounds(), 
					choices, model.getSignedInAs().getName(), model.getSignedInAs().getPassword());
			System.out.println("ClosedCreateRequest sent");
		}
		
		/*if (choice == null || choice.length() == 0)
		{
			System.err.println("Please do not leave choice blank.");//return error message here, empty choice
			return false;
		}

		for (int t = 0; t < model.numLines; t++)
		{
			if (a1gui.choices[t].getText().equals(a1gui.choices[j].getText()) && t != j)
			{
				System.err.println("This is the same choice as before.  Give yourselves variety, change your choice.");
				return false;
			}	
		}	
		model.lines[j].choice = a1gui.getChoice(j).getText(); //assign value from JtextField to Line
		return true;*/
	}
}
